package com.sobey.web.config;

import javax.servlet.Filter;

import org.springframework.core.annotation.Order;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.sobey.web.core.SB_SpringContext;

/*
 * 所有实现了WebApplicationInitializer接口的类都会在容器启动时自动被加载运行，用@Order注解设定加载顺序
 * 这是servlet3.0+后加入的特性，web.xml中可以不需要配置内容，都硬编码到WebApplicationInitializer的实现类中
 * 
 * spring DispatcherServlet的配置,其它servlet和监听器等需要额外声明，用@Order注解设定启动顺序
 */
@Order(3)
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

	/**
	 * 应用上下文, 除Web部分
	 */
	@Override
	protected Class[] getRootConfigClasses() {
		return new Class[] {AppConfig.class};
	}

	/**
	 *  web上下文配置
	 */
	@Override
	protected Class[] getServletConfigClasses() {
		return new Class[] {MvcConfig.class};
	}

	/**
	 * DispatcherServlet的映射路径
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}

	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		return new Filter[] {characterEncodingFilter};
	}

	/**
	 * 创建一个可以在非spring管理bean中获取spring管理相关的bean对象: 
	 */
	@Override
	protected WebApplicationContext createRootApplicationContext() {
		WebApplicationContext ctx = super.createRootApplicationContext();
		SB_SpringContext.getInstance().setApplicationContext(ctx);
		return ctx;
	}
}
